package com.lsl.rdf.config;

import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.function.Consumer;

/**
 * 事务回调接口
 * <p>
 * Created by lsl on 2021/4/8.
 */
@Component
public class TransactionCallBackService {
    /**
     * 没有事务
     */
    int NONE_TRANSACTION = 3;

    /**
     * 事务提交后回调
     */
    public void afterCommit(Consumer<Boolean> consumer) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new TransactionSynchronization() {

                        @Override
                        public void afterCommit() {
                            consumer.accept(Boolean.TRUE);
                        }
                    });
        } else {
            consumer.accept(Boolean.FALSE);
        }
    }

    /**
     * 事务执行完成后回调
     */
    public void afterCompletion(Consumer<Integer> consumer) {
        if (TransactionSynchronizationManager.isActualTransactionActive()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new TransactionSynchronization() {

                        @Override
                        public void afterCompletion(int status) {
                            consumer.accept(status);
                        }
                    });
        } else {
            consumer.accept(NONE_TRANSACTION);
        }
    }
}
